package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessAuthentication;
import com.digitalchina.lxnsy.api.BusinessExpert;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.ExpertTitleVO;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.ExpertInfoXML;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/7/21 17:28
 * 修改备注：
 * ================================================
 */
public class AuthenticationInfoActivity extends BaseActivity {
    @Bind(R.id.tv_expert_true_name)
    TextView tvExpertTrueName;
    @Bind(R.id.tv_expert_title)
    TextView tvExpertTitle;
    @Bind(R.id.tv_expert_title_number)
    TextView tvExpertTitleNumber;
    @Bind(R.id.iv_expert_title_photo)
    SimpleDraweeView ivExpertTitlePhoto;
    @Bind(R.id.tv_expert_id_number)
    TextView tvExpertIdNumber;
    @Bind(R.id.iv_expert_id_photo)
    SimpleDraweeView ivExpertIdPhoto;

    private String trueName = "";
    private String expertTitleId = "";
    private String titleNumber = "";
    private String expertTitleImage = "";
    private String idCardNo = "";
    private String idCardImage = "";
    private int fileType = -1;  // 0-头像 1-职称照片 2-身份证照片
    private String filePath = ""; // 图片地址
    private ArrayList<ImageItem> selectedImageList = new ArrayList<>(); //当前选择的所有图片
    public static final int REQUEST_CODE_EDIT = 99;
    public static final int REQUEST_CODE_SELECT = 100;

    private boolean isUpdate = false;

    // 专家职称List
    private List<ExpertTitleVO> expertTitleVOList = new ArrayList<>();
    // 专家职称选择器
    private OptionsPickerView pvExpertTitle;
    private int msgWhat;

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_authentication_info);
        setTitle("认证信息");
    }

    @Override
    public void initMember() {
        initValue();
    }

    /**
     * 初始化数组
     */
    private void initValue() {

        trueName = ExpertInfoXML.getExpertName(this);
        expertTitleId = ExpertInfoXML.getExpertTitleCode(this);
        titleNumber = ExpertInfoXML.getExpertTitleNum(this);
        expertTitleImage = ExpertInfoXML.getExpertTitleImage(this);
        idCardNo = ExpertInfoXML.getIdCardNum(this);
        idCardImage = ExpertInfoXML.getIdCardImage(this);


        tvExpertTrueName.setText(trueName);
        tvExpertTitle.setText(ExpertInfoXML.getExpertTitleName(this));
        tvExpertTitleNumber.setText(titleNumber);
        tvExpertIdNumber.setText(idCardNo);

        FrescoUtil.showImageSmall(expertTitleImage, ivExpertTitlePhoto);
        FrescoUtil.showImageSmall(idCardImage, ivExpertIdPhoto);

    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                dismissDialog();
                msgWhat = msg.what;
                switch (msgWhat) {
                    case MSG.MSG_FILE_UPLOAD_SUCCESS:  // 上传图片
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_SAVE_AUTHENTICATION_INFO_SUCCESS: // 提交成功
                        showToast("提交成功");
                        ActivityTaskManager.getInstance().closeActivity(AccountExpertManagementActivity.class);
                        finish();
                        break;
                    case MSG.MSG_SAVE_EXPERT_INFO_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_EXPERT_TITLE_LIST_SUCCESS: // 获取专家职称接口
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_EXPERT_TITLE_LIST_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        switch (msgWhat) {
            case MSG.MSG_FILE_UPLOAD_SUCCESS:  // 上传图片成功后 返回FileName
                FileVO fileVO = FastJsonUtil.getBean(object.toString(), "body", "fileStorage", FileVO.class);
                if (fileVO == null)
                    return;
                switch (fileType) {
                    case 0:
                        break;
                    case 1:
                        expertTitleImage = fileVO.getName();
                        FrescoUtil.showImageSmall(expertTitleImage, ivExpertTitlePhoto);
                        isUpdate = true;
                        break;
                    case 2:
                        idCardImage = fileVO.getName();
                        FrescoUtil.showImageSmall(idCardImage, ivExpertIdPhoto);
                        isUpdate = true;
                        break;
                }
                break;
            case MSG.MSG_EXPERT_TITLE_LIST_SUCCESS: // 获取专家职称接口
                expertTitleVOList = FastJsonUtil.getListBean(object.toString(), "titleList", ExpertTitleVO.class);
                if (expertTitleVOList != null && expertTitleVOList.size() > 0) {
                    initExpertTitleData();
                    pvExpertTitle.show();
                } else
                    showToast("获取专家职称失败");
                break;
        }
    }

    /**
     * 专家职称选择器
     */
    private void initExpertTitleData() {

        pvExpertTitle = new OptionsPickerView.Builder(AuthenticationInfoActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                String select = expertTitleVOList.get(options1).getPickerViewText();
                tvExpertTitle.setText(select);
                expertTitleId = expertTitleVOList.get(options1).getId();
                isUpdate = true;
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        pvExpertTitle.setPicker(expertTitleVOList);
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 修改头像跳转至自定义相册
     */
    private void selectImage(int fileType) {
        this.fileType = fileType;
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setMultiMode(false);    //是否多选模式
        imagePicker.setCrop(false);
        Intent intent = new Intent(this, ImageGridActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SELECT);
    }

    /**
     * 跳转回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null && requestCode == REQUEST_CODE_EDIT) {

            switch (data.getStringExtra("type")) {
                case "trueName": // 真实姓名
                    trueName = data.getStringExtra("edit");
                    tvExpertTrueName.setText(trueName);
                    isUpdate = true;
                    break;
                case "titleNumber": // 专家职称号
                    titleNumber = data.getStringExtra("edit");
                    tvExpertTitleNumber.setText(titleNumber);
                    isUpdate = true;
                    break;
                case "idCardNo": // 身份证号
                    idCardNo = data.getStringExtra("edit");
                    tvExpertIdNumber.setText(idCardNo);
                    isUpdate = true;
                    break;
            }

        } else if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                showDialog("上传中,请稍候!");
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                filePath = images.get(0).path;
                selectedImageList.addAll(images);
                BusinessFile.imageCompressAndUpload(AuthenticationInfoActivity.this, filePath, mHandler);
            }
        }
    }

    @OnClick({R.id.rl_expert_true_name, R.id.rl_expert_title, R.id.rl_expert_title_number, R.id.rl_expert_title_photo, R.id.rl_expert_id_number, R.id.rl_expert_id_photo, R.id.btn_expert_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_expert_true_name:
                gotoEditActivity("trueName", trueName);
                break;
            case R.id.rl_expert_title:
                getExpertTitle();
                break;
            case R.id.rl_expert_title_number:
                gotoEditActivity("titleNumber", titleNumber);
                break;
            case R.id.rl_expert_title_photo:
                selectImage(1);
                break;
            case R.id.rl_expert_id_number:
                gotoEditActivity("idCardNo", idCardNo);
                break;
            case R.id.rl_expert_id_photo:
                selectImage(2);
                break;
            case R.id.btn_expert_submit:
                submitValue();
                break;
        }
    }

    /**
     * 获取专家职称
     */
    private void getExpertTitle() {
        if (expertTitleVOList.size() <= 0) {
            BusinessExpert.expertTitleList(this, mHandler);
        } else
            pvExpertTitle.show();
    }

    /**
     * 跳转到编辑页面
     *
     * @param type 标记修改的类型
     */
    private void gotoEditActivity(String type, String content) {
        Intent intent = new Intent(AuthenticationInfoActivity.this, EditExpertInfoActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("content", content);
        startActivityForResult(intent, REQUEST_CODE_EDIT);
    }

    private void submitValue() {

        if (!isUpdate) {
            showToast("无修改信息!");
            return;
        }

        if (ExpertInfoXML.getIsAudit(this).equals("2") || ExpertInfoXML.getIsChangeAudit(this).equals("2")) {
            CustomDialog.nativeDialog(this, "正在审核中，无法提交！");
            return;
        }

        if (StringUtil.isStrEmpty(trueName)) {
            showToast("请输入真实姓名");
            return;
        }
        if (StringUtil.isStrEmpty(expertTitleId)) {
            showToast("请选择专家职称");
            return;
        }

        if (StringUtil.isStrEmpty(titleNumber) || StringUtil.isStrEmpty(expertTitleImage)) {
            if (StringUtil.isStrEmpty(idCardNo) || StringUtil.isStrEmpty(idCardImage)) {
                showToast("专家职称信息与身份信息两组至少填写一组");
                return;
            }
        }


        BusinessAuthentication.saveAuthenticationInfo(this, trueName, expertTitleId, titleNumber, expertTitleImage, idCardNo, idCardImage, mHandler);
    }
}
